"""
应用配置管理
"""

import os
from typing import List, Dict, Any

from dotenv import load_dotenv
from pydantic import ConfigDict
from pydantic_settings import BaseSettings

# 加载.env文件
load_dotenv()


class Settings(BaseSettings):
    """应用配置类"""

    # 基础配置
    APP_NAME: str = "RTZL AI Web"
    VERSION: str = "1.0.0"
    DEBUG: bool = False
    HOST: str = "0.0.0.0"
    PORT: int = 8800

    # CORS配置
    @property
    def ALLOWED_ORIGINS(self) -> List[str]:
        if self.DEBUG:
            # 开发环境：允许所有来源
            return ["*"]
        else:
            # 生产环境：只允许特定来源
            return [
                "http://localhost:3000",
                "http://127.0.0.1:3000",
                "http://localhost:5173",
                "http://127.0.0.1:5173",
                "http://192.168.132.63:3000",
                "http://192.168.132.63:5173",
                # 添加您的生产域名
                # "https://yourdomain.com"
            ]

    # 数据库配置
    MYSQL_HOST: str = os.getenv("MYSQL_HOST", "localhost")
    MYSQL_PORT: int = int(os.getenv("MYSQL_PORT", 3306))
    MYSQL_USER: str = os.getenv("MYSQL_USER", "root")
    MYSQL_PASSWORD: str = os.getenv("MYSQL_PASSWORD", "password")
    MYSQL_DATABASE: str = os.getenv("MYSQL_DATABASE", "ruitong_zhilian")

    @property
    def DATABASE_URL(self) -> str:
        return f"mysql+pymysql://{self.MYSQL_USER}:{self.MYSQL_PASSWORD}@{self.MYSQL_HOST}:{self.MYSQL_PORT}/{self.MYSQL_DATABASE}"

    # Redis配置
    REDIS_HOST: str = os.getenv("REDIS_HOST", "localhost")
    REDIS_PORT: int = int(os.getenv("REDIS_PORT", 6379))
    REDIS_DB: int = int(os.getenv("REDIS_DB", 0))
    REDIS_PASSWORD: str = os.getenv("REDIS_PASSWORD", "")

    @property
    def REDIS_URL(self) -> str:
        if self.REDIS_PASSWORD:
            return f"redis://:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
        return f"redis://{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"

    # 文件上传配置
    UPLOAD_DIR: str = "uploads"
    MAX_FILE_SIZE: int = 10 * 1024 * 1024  # 10MB
    ALLOWED_FILE_TYPES: List[str] = [
        "image/jpeg", "image/png", "image/gif",
        "application/pdf", "text/plain", "application/json"
    ]

    # MCP服务器配置
    def get_mcp_servers_from_db(self) -> Dict[str, Dict[str, Any]]:
        """从数据库中获取MCP服务器配置"""
        try:
            # 延迟导入避免循环依赖
            from sqlalchemy import create_engine, text
            from sqlalchemy.orm import sessionmaker

            # 创建数据库连接
            engine = create_engine(self.DATABASE_URL, pool_pre_ping=True)
            SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

            servers = {}

            with SessionLocal() as session:
                try:
                    # 使用原生SQL查询，避免模型导入问题
                    query = text("""
                        SELECT mcp_name, json_schema 
                        FROM ai_web_mcp_tools 
                        WHERE status = 1 AND json_schema IS NOT NULL
                    """)

                    result = session.execute(query)
                    rows = result.fetchall()

                    for row in rows:
                        mcp_name = row[0]
                        json_schema_str = row[1]

                        if json_schema_str:
                            try:
                                # 解析JSON配置
                                if isinstance(json_schema_str, str):
                                    import json
                                    json_schema = json.loads(json_schema_str)
                                else:
                                    # 如果已经是dict类型（某些数据库驱动会自动解析JSON）
                                    json_schema = json_schema_str

                                if isinstance(json_schema, dict) and json_schema:
                                    servers[mcp_name] = json_schema

                            except Exception as parse_error:
                                print(f"解析MCP工具 {mcp_name} 的JSON配置失败: {parse_error}")
                                continue

                    if servers:
                        print(f"从数据库成功加载 {len(servers)} 个MCP服务器配置")

                except Exception as query_error:
                    print(f"查询数据库MCP配置时出错: {query_error}")
                    return {}

            return servers

        except Exception as e:
            print(f"连接数据库获取MCP服务器配置失败: {e}")
            return {}

    @property
    def DEFAULT_MCP_SERVERS(self) -> Dict[str, Dict[str, Any]]:
        """获取默认的MCP服务器配置
        
        优先级：
        1. 数据库中的已上线MCP工具配置
        2. 环境变量中的JSON配置
        3. 环境变量中的单独配置
        4. 空配置
        """
        # 1. 优先从数据库获取MCP服务器配置
        try:
            db_servers = self.get_mcp_servers_from_db()
            if db_servers:
                return db_servers
        except Exception as e:
            print(f"从数据库获取MCP配置时出错: {e}")
        return {}

    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "logs/app.log"

    model_config = ConfigDict(
        env_file="..env",
        env_file_encoding="utf-8"
    )

    DEFAULT_SCENE_ID: str = "ada5d384-ed0d-44e5-bbbe-1173c8dc2830"  # 默认场景ID
    DEFAULT_AGENT_ID: str = "74f7552c-7a36-4349-b79b-5b26ff773a6a"  # 默认Agent ID
    DEFAULT_EMBEDDING_MODEL: str = "dashscope-text-embedding-v4"  # 默认向量模型

    # ChromaDB 配置
    CHROMA_DB_PATH: str = os.getenv("CHROMA_DB_PATH", "./catch/ai_web")
    CHROMA_COLLECTION_NAME: str = os.getenv("CHROMA_COLLECTION_NAME", "ai_web_vectors")
    CHROMA_EMBEDDING_MODEL: str = os.getenv("CHROMA_EMBEDDING_MODEL", "dashscope-text-embedding-v4")

    # 智谱AI 配置
    ZHIPU_API_KEY: str = os.getenv("ZHIPU_API_KEY", "")

    # chrome浏览器配置
    GOOGLE_DRIVER_PATH: str = os.getenv("GOOGLE_DRIVER_PATH", "./catch/chromedriver.exe")


# 创建全局配置实例
settings = Settings()
